package com.joey.cloud.zuul.filter;

import cn.hutool.core.util.IdUtil;
import com.joey.cloud.communal.constant.BaseConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

/**
 * 追踪过滤器
 * @author joey
 */
@Component
public class TraceFilter extends ZuulFilter {

    /**
     * pre=路由之前；routing=路由之时；post=路由之后；error=发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return BaseConstant.FILTER_TYPE_PRE;
    }

    /**
     * 过滤的顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 这里可以写逻辑判断，是否要过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.getRequest().setAttribute(BaseConstant.TRACT_ID, IdUtil.getSnowflake(0, 0).nextId());
        return true;
    }

}
